package com.example.app02
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import java.io.File

class MainActivity : AppCompatActivity() {
    private lateinit var etInput: EditText
    private lateinit var tvResult: TextView
    private lateinit var ivPhoto: ImageView  // 照片显示控件
    private var currentPhotoUri: Uri? = null  // 记录当前照片Uri

    // 注册Activity2返回结果
    private val activity2ResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val returnData = result.data?.getStringExtra("return_data") ?: "无数据"
            tvResult.text = "Activity2返回：$returnData"
        }
    }

    // 注册Activity3（拍照）返回结果
    private val cameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // 接收Activity3返回的照片Uri
            currentPhotoUri = result.data?.data
            // 显示照片
            currentPhotoUri?.let { uri ->
                val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
                ivPhoto.setImageBitmap(bitmap)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化控件
        etInput = findViewById(R.id.etInput)
        tvResult = findViewById(R.id.tvResult)
        ivPhoto = findViewById(R.id.ivPhoto)  // 绑定照片显示控件

        // 启动Activity1
        findViewById<Button>(R.id.btnActivity1).setOnClickListener {
            val inputText = etInput.text.toString().ifEmpty { "默认内容" }
            val intent = Intent(this, Activity1::class.java)
            intent.putExtra("param", inputText)
            startActivity(intent)
        }

        // 启动Activity2
        findViewById<Button>(R.id.btnActivity2).setOnClickListener {
            activity2ResultLauncher.launch(Intent(this, Activity2::class.java))
        }

        // 启动Activity3（拍照）
        findViewById<Button>(R.id.btnActivity3).setOnClickListener {
            val intent = Intent(this, Activity3::class.java)
            cameraResultLauncher.launch(intent)  // 用相机结果 launcher 启动
        }

        // 启动Activity4
        findViewById<Button>(R.id.btnActivity4).setOnClickListener {
            startActivity(Intent(this, Activity4::class.java))
        }
    }
}